// pages/shopCart/shopCart.js
const { cartList, changeCartItemCount, deleteCartList } = require('../../api/url.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    showModal: false,//是否显示授权模态框
    shopCartItems: [],//购物车列表
    totalPri: 0,//总价格
    totalPriTxt: '0.00',//显示总价格
    isSelectAll: false,//是否全选
    selectedCount: 0,//选择的数量
    isEdit: false,//是否处于编辑状态
    noOnSale:[],//下架商品
    page:1,//请求第几页
    size:20,//每页请求数据量
    loadOver:false,//是否请求完所有数据
  },
  /**
   * @method
   * @desc 删除下架商品
   */
  delNone(e){
    let that=this
    console.log(e)
    wx.showModal({
      title: '温馨提醒',
      content: '您确定要删除吗？',
      success(res) {
        if (res.confirm) {
          let ids = e.currentTarget.dataset.id
          wx.request({
            url: deleteCartList,
            data: {
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              ids: ids
            },
            success(res) {
              if (res.data.code === 0) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'none'
                })
                let temList = that.data.noOnSale.filter(val => val.fId != e.currentTarget.dataset.id)
                that.setData({
                  noOnSale: temList
                })
                // that.setSelectedCount()
                // that.calTotalPri()
              } else {
                wx.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }
            }
          })
        }
      }
    })
  },
  /**
   * @method
   * @desc 返回首页
   */
  goIndex(){
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  /**
   * @method
   * @desc 去结算或是去删除
   */
  goOrderConfirm() {
    let that = this
    if (that.data.selectedCount>0){
      if (that.data.isEdit) {
        //删除
        wx.showModal({
          title: '温馨提醒',
          content: '您确定要删除吗？',
          success(res) {
            if (res.confirm) {
              let temList = that.data.shopCartItems
              let idsArray = that.data.shopCartItems.filter(val => val.selected).map(val => val.fid)
              let ids = idsArray.join(',')
              wx.request({
                url: deleteCartList,
                data: {
                  loginName: app.globalData.userInfo.loginname,
                  token: wx.getStorageSync('token'),
                  ids: ids
                },
                success(res) {
                  if (res.data.code === 0) {
                    wx.showToast({
                      title: '删除成功',
                      icon: 'none'
                    })
                    idsArray.map(val => {
                      temList = temList.filter(val1 => val1.fId != val)
                    })

                    that.setData({
                      shopCartItems: temList
                    })
                    that.setSelectedCount()
                    that.calTotalPri()
                  } else {
                    wx.showToast({
                      title: '删除失败',
                      icon: 'none'
                    })
                  }
                }
              })
            }
          }
        })
      } else {
        //去结算
        let that = this
        let selected = that.data.shopCartItems.filter(val => val.selected)
        if (selected.length > 0) {
          let skuInfo = selected.map(val => `${val.fproductId}:${val.fproductRuleId ? val.fproductRuleId:0}:${val.fCount}`).join(';')
          wx.navigateTo({
            url: `../confirmOrder/confirmOrder?data=${skuInfo}&fromCart=1`
          })
        } else {
          wx.showToast({
            title: '您还未选中任何商品',
            icon: 'none'
          })
        }
      }
    }else{
      wx.showToast({
        title: '您还没有选择任何商品哦~',
        icon:'none'
      })
    }
    
  },
  /**
   * @method
   * @desc 切换编辑和购物车
   */
  toggleEdit() {
    let that = this
    that.setData({
      isEdit: !that.data.isEdit
    })
  },
  /**
   * @method
   * @desc 设置选择的数量
   */
  setSelectedCount() {
    let that = this
    that.setData({
      selectedCount: that.data.shopCartItems.filter(val => val.selected).length
    })
  },
  /**
   * @method
   * @desc 全选
   */
  selectAll() {
    let that = this
    that.setData({
      isSelectAll: !that.data.isSelectAll
    })
    let temList = that.data.shopCartItems
    if (that.data.isSelectAll) {
      temList.forEach(val => {
        val.selected = true
      })
    } else {
      temList.forEach(val => {
        val.selected = false
      })
    }
    that.setData({
      shopCartItems: temList
    })
    that.calTotalPri()
    that.setSelectedCount()
  },
  /**
   * @method
   * @desc 判断是否全选
   */
  isSelectAll() {
    let that = this
    let selected = that.data.shopCartItems.filter(val => val.selected)
    if (selected.length === that.data.shopCartItems.length) {
      that.setData({
        isSelectAll: true
      })
    } else {
      that.setData({
        isSelectAll: false
      })
    }
  },
  /**
   * @method
   * @desc 选择购物车项
   */
  selectItem(e) {
    let that = this
    let id = e.currentTarget.dataset.id,
      temLists = that.data.shopCartItems
    temLists.forEach((val) => {
      if (val.fId === id) {
        val.selected = val.selected ? !val.selected : true
      }
    })
    that.setData({
      shopCartItems: temLists
    })
    that.isSelectAll()
    that.calTotalPri()
    that.setSelectedCount()
  },
  /**
   * @method
   * @desc 计算总价格
   */
  calTotalPri() {
    let that = this
    let temItems = that.data.shopCartItems.filter(val => val.selected)
    if (temItems.length > 0) {
      that.setData({
        totalPri: temItems.map(val => val.pri * val.fCount).reduce(function (val1, val2) {
          return val1 + val2
        })
      })
      that.setData({
        totalPriTxt: that.data.totalPri.toFixed(2)
      })
    } else {
      that.setData({
        totalPriTxt: '0.00',
        totalPri: 0
      })
    }

  },
  /**
   * @method
   * @desc 修改购物车数量
   */
  updateCount(e) {
    let that = this
    let type = e.currentTarget.dataset.type,
      count = e.currentTarget.dataset.count,
      goodsId = e.currentTarget.dataset.goodsid,
      totalCount = e.currentTarget.dataset.totalcount
    switch (type) {
      case 'minus':
        //减
        if (count > 1) {
          wx.showLoading({
            title: '加载中',
            mask: true
          })
          wx.request({
            url: changeCartItemCount,
            data: {
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              fId: goodsId,
              fCount: --count
            },
            success(res) {
              wx.hideLoading()
              if (res.data.code === 0) {
                let temList = that.data.shopCartItems
                temList.forEach(val => {
                  if (val.fId === goodsId) {
                    --val.fCount
                  }
                })
                that.setData({
                  shopCartItems: temList
                })
                that.calTotalPri()
              } else {
                wx.showToast({
                  title: '修改失败',
                  icon: 'none'
                })
              }
            },
            fail() {
              wx.hideLoading()
              wx.showToast({
                title: '修改数量失败',
                icon: 'none'
              })
            }
          })
        }
        break
      case 'plus':
        //加
        if (count < totalCount) {
          wx.showLoading({
            title: '加载中',
            mask: true
          })
          wx.request({
            url: changeCartItemCount,
            data: {
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              fId: goodsId,
              fCount: ++count
            },
            success(res) {
              wx.hideLoading()
              if (res.data.code === 0) {
                let temList = that.data.shopCartItems
                temList.forEach(val => {
                  if (val.fId === goodsId) {
                    ++val.fCount
                  }
                })
                that.setData({
                  shopCartItems: temList
                })
                that.calTotalPri()
              } else {
                wx.showToast({
                  title: '修改失败',
                  icon: 'none'
                })
              }
            },
            fail() {
              wx.hideLoading()
              wx.showToast({
                title: '修改数量失败',
                icon: 'none'
              })
            }
          })
        } else {
          wx.showToast({
            title: '库存不够辣',
            icon: 'none'
          })
        }
        break
      case 'input':
        //输入
        let inputCount = Number(e.detail.value)
        if (inputCount <= totalCount && inputCount >= 1) {
          wx.showLoading({
            title: '加载中',
            mask: true
          })
          wx.request({
            url: changeCartItemCount,
            data: {
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              fId: goodsId,
              fCount: inputCount
            },
            success(res) {
              wx.hideLoading()
              if (res.data.code === 0) {
                let temList = that.data.shopCartItems
                temList.forEach(val => {
                  if (val.fId === goodsId) {
                    val.fCount = inputCount
                  }
                })
                that.setData({
                  shopCartItems: temList
                })
                that.calTotalPri()
              } else {
                wx.showToast({
                  title: '修改失败',
                  icon: 'none'
                })
              }
            },
            fail() {
              wx.hideLoading()
              wx.showToast({
                title: '修改数量失败',
                icon: 'none'
              })
            }
          })
        } else if (inputCount < 1) {
          wx.showLoading({
            title: '数量不正确',
            mask: true
          })
          wx.request({
            url: changeCartItemCount,
            data: {
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              fId: goodsId,
              fCount: 1
            },
            success(res) {
              wx.hideLoading()
              if (res.data.code === 0) {
                let temList = that.data.shopCartItems
                temList.forEach(val => {
                  if (val.fId === goodsId) {
                    val.fCount = 1
                  }
                })
                that.setData({
                  shopCartItems: temList
                })
                that.calTotalPri()
              } else {
                wx.showToast({
                  title: '修改失败',
                  icon: 'none'
                })
              }
            },
            fail() {
              wx.hideLoading()
              wx.showToast({
                title: '修改数量失败',
                icon: 'none'
              })
            }
          })
        } else if (inputCount > totalCount) {
          wx.showLoading({
            title: '库存不足',
            mask: true
          })
          wx.request({
            url: changeCartItemCount,
            data: {
              loginName: app.globalData.userInfo.loginname,
              token: wx.getStorageSync('token'),
              fId: goodsId,
              fCount: totalCount
            },
            success(res) {
              wx.hideLoading()
              if (res.data.code === 0) {
                let temList = that.data.shopCartItems
                temList.forEach(val => {
                  if (val.fId === goodsId) {
                    val.fCount = totalCount
                  }
                })
                that.setData({
                  shopCartItems: temList
                })
                that.calTotalPri()
              } else {
                wx.showToast({
                  title: '修改失败',
                  icon: 'none'
                })
              }
            },
            fail() {
              wx.hideLoading()
              wx.showToast({
                title: '修改数量失败',
                icon: 'none'
              })
            }
          })
        }
        break
    }
  },
  /**
   * @method
   * 授权回调
   */
  settingCB(res) {
    let that = this
    if (res.detail.detail.errMsg === 'getUserInfo:ok') {
      app.globalData.wxUserInfo = res.detail.detail.userInfo
      wx.showLoading({
        title: '用户登录',
        mask: true
      })
      app.getUserInfo().then(res => {
        wx.hideLoading()
        that.setData({
          showModal: false
        })
        if (res.data.code === 0) {
          //做其它操作
          that.loadItems()
        } else {
          wx.showToast({
            title: '用户登录失败',
            icon: 'none'
          })
        }
      })
    } else {
      that.setData({
        showModal: false
      })
    }
  },
  /**
   * @method
   * @desc 关闭模态框
   */
  closeModal() {
    let that = this
    that.setData({
      showModal: false
    })
  },
  /**
   * @method 
   * @desc 加载购物车数据
   */
  loadItems() {
    let that = this
    if(!that.data.loadOver){
      wx.showLoading({
        title: '加载中',
        mask: true
      })
      wx.request({
        url: cartList,
        data: {
          loginName: app.globalData.userInfo.loginname,
          token: wx.getStorageSync('token'),
          page: that.data.page,
          size: that.data.size,
          fType: 0
        },
        success(res) {
          wx.hideLoading()
          if (res.data.code === 0) {
            let temList = res.data.response.cont.list
            if(temList.length<that.data.size){//请求完所有数据
              that.setData({
                loadOver:true,
                page:that.data.page+1
              })
            }else{//未请求完所有数据
              that.setData({
                loadOver: false,
                page: that.data.page + 1
              })
            }
            temList = res.data.response.cont.list.filter(val => val.product.fTotalCount > 0)
            temList = temList.filter(val => {
              if (val.skuList && val.skuList.length > 0) {
                let temSku = val.skuList.find(val1 => {
                  return (val1.fId + '') === val.fProductRuleId
                })
                return temSku.fStock > 0
              } else {
                return true
              }
            })
            temList.forEach(val => {
              val.img = app.globalData.imageBaseUrl + val.product.fMainPicture
              if (val.categoryPropertyVal && val.categoryPropertyVal.length > 0) {
                val.skuStr = val.categoryPropertyVal.map(val1 => {
                  return val1.propertyName + ':' + val1.fName
                }).join(';')
              } else {
                val.skuStr = '默认规格'
              }
              if (val.skuList && val.skuList.length > 0 && val.fproductRuleId) {
                val.pri = val.skuList.filter(val1 => {
                  return val1.fId === Number(val.fproductRuleId)
                })[0].fPrice
                val.priTxt = val.pri.toFixed(2)
              } else {
                val.pri = val.product.fFixedPrice
                val.priTxt = val.pri.toFixed(2)
              }
            })
            that.setData({
              noOnSale: that.data.noOnSale.concat(temList.filter(val => val.fstate == 1))
            })
            temList = temList.filter(val => val.fstate != 1)
            that.setData({
              shopCartItems: that.data.shopCartItems.concat(temList) 
            })
            that.calTotalPri()
          }else{
            wx.showToast({
              title: '加载购物车异常',
              icon:'none'
            })
          }
        },
        fail(){
          wx.hideLoading()
          wx.showToast({
            title: '加载购物车失败',
            icon:'none'
          })
        }
      })
    }else{
      wx.showToast({
        title: '已加载完数据',
        icon:'none'
      })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this
    that.setData({
      showModal: false,//是否显示授权模态框
      shopCartItems: [],//购物车列表
      totalPri: 0,//总价格
      totalPriTxt: '0.00',//显示总价格
      isSelectAll: false,//是否全选
      selectedCount: 0,//选择的数量
      isEdit: false,//是否处于编辑状态
      noOnSale: [],//下架商品
      page: 1,//请求第几页
      loadOver: false,//是否请求完所有数据
    })
    app.userLogin().then(res => {
      wx.hideLoading()
      if (res === 'noAuthorize') {
        that.setData({
          showModal: true
        })
      } else if (res === 'success') {
        that.setData({
          showModal: false
        })
        //做其它请求
        //请求购物车数据
        that.loadItems()

      } else if (res === 'fail') {
        that.setData({
          showModal: false
        })
        wx.showToast({
          title: '注册用户失败',
          icon: 'none'
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let that=this
    that.setData({
      showModal: false,//是否显示授权模态框
      shopCartItems: [],//购物车列表
      totalPri: 0,//总价格
      totalPriTxt: '0.00',//显示总价格
      isSelectAll: false,//是否全选
      selectedCount: 0,//选择的数量
      isEdit: false,//是否处于编辑状态
      noOnSale: [],//下架商品
      page: 1,//请求第几页
      loadOver: false,//是否请求完所有数据
    })
    that.loadItems()
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let that=this
    that.loadItems()
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})